package com.rivues.module.report.web.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.avro.data.Json;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.web.servlet.ModelAndView;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.handler.Handler;
import com.rivues.module.platform.web.model.AnalyzerReport;
import com.rivues.module.platform.web.model.AnalyzerReportModel;
import com.rivues.module.platform.web.model.Cube;
import com.rivues.module.platform.web.model.CubeLevel;
import com.rivues.module.platform.web.model.DataDic;
import com.rivues.module.platform.web.model.Dimension;
import com.rivues.module.platform.web.model.PublishedCube;
import com.rivues.module.platform.web.model.QueryLog;
import com.rivues.module.platform.web.model.QueryText;
import com.rivues.module.platform.web.model.ReportFilter;
import com.rivues.module.platform.web.model.ReportModel;
import com.rivues.module.platform.web.model.ReportOperations;
import com.rivues.module.platform.web.model.User;
import com.rivues.module.report.web.model.PublishedReport;
import com.rivues.util.RivuTools;
import com.rivues.util.data.FirstTitle;
import com.rivues.util.data.Level;
import com.rivues.util.data.ReportData;
import com.rivues.util.data.ValueData;
import com.rivues.util.datasource.DataSource;
import com.rivues.util.exception.ReportException;
import com.rivues.util.iface.cube.CubeFactory;
import com.rivues.util.iface.report.ReportFactory;
import com.rivues.util.serialize.JSON;
import com.rivues.util.service.ServiceHelper;
import com.rivues.util.service.cache.CacheHelper;

public class ReportHandler extends Handler{
	/**
	 * 报表查询的日志记录
	 */
	public QueryLog queryLog ;

	public QueryLog getQueryLog() {
		return queryLog;
	}

	public void setQueryLog(QueryLog queryLog) {
		this.queryLog = queryLog;
	}
	
	public void updateCacheReport(HttpServletRequest request,PublishedReport report, AnalyzerReport analyzerReport , String orgi){
		updateCacheReport(request, report, analyzerReport, orgi , false);
		if(CacheHelper.getDistributedCacheBean().getCacheObject(RivuTools.genReportCacheID(report.getId() , super.getUser(request), true), orgi)!=null){
			updateCacheReport(request, report, analyzerReport, orgi , true);
		}
    }
	
	/**
	 *	 用于保存 model report 和 cube 的 使用关系
	 * @param savemodel
	 * @param reportid
	 * @param orgi
	 * @param report
	 */
	public void saveCubeInUser(AnalyzerReportModel savemodel , String reportid , String orgi , PublishedReport report){
		/**
    	 * 保存model 的 cube 记录
    	 */
		String rmid = RivuTools.md5(reportid) ;
    	if(savemodel!=null && savemodel.getPublishedcubeid()!=null){
    		ReportModel reportModel = null ;
    		List<ReportModel> modelList = super.getService().findAllByCriteria(DetachedCriteria.forClass(ReportModel.class).add(Restrictions.eq("id",rmid))) ;
    		if(modelList.size()>0){
	    		reportModel = modelList.get(0) ;
	    		reportModel.setId(rmid);
	    		reportModel.setOrgi(orgi);
	    		reportModel.setReportid(reportid);
    			reportModel.setName(report.getName());
    			
    			reportModel.setCreatetime(new Date());
    			reportModel.setTitle(this.getParent(report.getDicid(), orgi));
    			reportModel.setObjectid(report.getDicid());
    			reportModel.setRowdimension(savemodel.getRowdimension());
    			reportModel.setColdimension(savemodel.getColdimension());
    			reportModel.setMeasure(savemodel.getMeasure());
    			reportModel.setStylestr(savemodel.getName()); //使用的模型名称
    			reportModel.setDstype(savemodel.getPublishedcubeid());
    			
    			PublishedCube cube = CubeFactory.getCubeInstance().getCubeByID(savemodel.getPublishedcubeid());
    			if(cube!=null && cube.getCube()!=null){
    				reportModel.setCube(cube.getCube().getId());
    			}
	    		super.getService().updateIObject(reportModel);
    		}else{
    			reportModel = new ReportModel();
    			reportModel.setId(rmid);
    			reportModel.setOrgi(orgi);
    			reportModel.setReportid(reportid);
    			reportModel.setName(report.getName());
    			reportModel.setCreatetime(new Date());
    			reportModel.setTitle(this.getParent(report.getDicid(), orgi));
    			reportModel.setObjectid(report.getDicid());
    			reportModel.setRowdimension(savemodel.getRowdimension());
    			reportModel.setColdimension(savemodel.getColdimension());
    			reportModel.setMeasure(savemodel.getMeasure());
    			reportModel.setStylestr(savemodel.getName());	//使用的模型名称
    			reportModel.setDstype(savemodel.getPublishedcubeid());
    			
    			PublishedCube cube = CubeFactory.getCubeInstance().getCubeByID(savemodel.getPublishedcubeid());
    			if(cube!=null && cube.getCube()!=null){
    				reportModel.setCube(cube.getCube().getId());
    			}
    			
				super.getService().saveIObject(reportModel);
			}
    	}else{
    		if(savemodel!=null && savemodel.getPublishedcubeid()==null){
    			ReportModel reportModel = new ReportModel();
    			reportModel.setReportid(reportid);
    			reportModel.setId(rmid);
    			List<ReportModel> modelList = super.getService().findAllByCriteria(DetachedCriteria.forClass(ReportModel.class).add(Restrictions.eq("id",rmid))) ;
    			if(modelList.size()>0){
    				super.getService().deleteIObject(reportModel);
    			}
    		}
    	}
	}
	
	public void updateCacheReport(HttpServletRequest request,PublishedReport report, AnalyzerReport analyzerReport , String orgi  , boolean useSessionID){
    	/**
    	 * 将Report序列化，然后存入分布式缓存
    	 */
    	if(analyzerReport!=null){
    		report.setReportcontent(JSON.toJSONString(report.getReport()));	
			/**
    		 * 更新缓存
    		 */
        	/**
        	 * 将当期编辑的报表放入分布式缓存中，报表编辑器退出的时候需要清理该报表，同样的，在用户退出的时候，也需要清理缓存中的垃圾
        	 */
    		CacheHelper.getDistributedCacheBean().update(RivuTools.genReportCacheID(report.getId(), super.getUser(request) , useSessionID), orgi , report) ;
    		
    		/**
        	 * 将当期编辑的报表放入分布式缓存中，报表编辑器退出的时候需要清理该报表，同样的，在用户退出的时候，也需要清理缓存中的垃圾
        	 */
    		CacheHelper.getDistributedCacheBean().update(RivuTools.genReportCacheID(report.getId(), super.getUser(request) , true), orgi , report) ;
			
    	}
    }
	/**
     * 根据ID获取 Report Model
     * @param analyzerReport
     * @param modelid
     * @return
     */
	public AnalyzerReportModel getReportModel(AnalyzerReport analyzerReport , String modelid){
    	AnalyzerReportModel reportModel = null ;
    	for(AnalyzerReportModel model : analyzerReport.getModel()){
    		if(model.getId().equals(modelid)){
    			reportModel = model ;
    			break ;
    		}
    	}
    	return reportModel;
    }
	/**
     * 获取过滤条件的 下拉列表值
     * @param analyzerReport
     * @param model
     */
    public void fillFilterValue(AnalyzerReport analyzerReport  , boolean updateCache, boolean cache , AnalyzerReportModel model , HttpServletRequest request ,  boolean useStaticFilter){
    	if(analyzerReport!=null && analyzerReport.getFilters()!=null && analyzerReport.getFilters().size()>0){
    		for(ReportFilter filter : analyzerReport.getFilters()){//设置上一级的默认值
    			if(!StringUtils.isBlank(filter.getCascadeid())){
    				for(ReportFilter filter2 : analyzerReport.getFilters()){
    					if(filter2.getId().equals(filter.getCascadeid())){
    						filter2.setParentValue(filter.getRequestvalue()==null||(filter.getRequestvalue()!=null&&filter.getRequestvalue().trim().length()==0)?filter.getDefaultvalue():filter.getRequestvalue());
    						filter2.setParentFilter(filter);
    						break;
    					}
    				}
    				
    			}
    		}
    		for(ReportFilter filter : analyzerReport.getFilters()){
    			//取得没有格式的过滤器值
    			
    			if(filter.getDefaultvalue()!=null&& filter.getDefaultvalue().indexOf("].[")>-1){
    				String[] strs = filter.getDefaultvalue().replaceAll("\\]  ,  \\[", "(ooo)").replaceAll(",", "\\(-=-\\)").replaceAll("\\(ooo\\)", "\\],\\[").split(",");
    				StringBuffer sb = new StringBuffer();
    				for (String string : strs) {
    					string = string.replaceAll(",", "\\(-=-\\)");
						if(sb.toString().length()>0){
							sb.append(",");
						}
						string = string.replaceAll("\\(-=-\\)", ",");
						sb.append(string.substring(string.lastIndexOf("["), string.length()).trim());
					}
    				filter.setNoformatvalue(sb.toString());
    			}else{
    				filter.setNoformatvalue(filter.getDefaultvalue());
    			}
    			if(filter.getRequestvalue()!=null){
    				if(filter.getRequestvalue().indexOf("].[")>-1){
    					String[] strs = filter.getRequestvalue().split(",");
        				StringBuffer sb = new StringBuffer();
        				for (String string : strs) {
        					string = string.trim();
    						if(sb.toString().length()>0){
    							sb.append(",");
    						}
    						sb.append(string.substring(string.lastIndexOf("["), string.length()).trim());
    					}
        				filter.setNoformatvalue(sb.toString());
    				}else{
    					filter.setNoformatvalue(filter.getRequestvalue());
    				}
    			}
    			if(filter.getNoformatvalue()!=null){
    				filter.setNoformatvalue(filter.getNoformatvalue().replace("[", "'"));
        			filter.setNoformatvalue(filter.getNoformatvalue().replace("]", "'"));
    			}
    			//取得没有格式的过滤器值end
    			
    			if(filter.getParentFilter()!=null&&StringUtils.isBlank(filter.getParentValue())) continue;
    			
    			if(model==null || !model.getId().equals(filter.getModelid())){
    				model = getReportModel(analyzerReport  , filter.getModelid()) ;
    			}
    			if(model!=null && filter.getReportData()==null && RivuDataContext.FilterConValueType.AUTO.toString().equals(filter.getConvalue())){
    				PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(model.getPublishedcubeid()) ;
	    			Cube cube = publishedCube.getCube() ;
	    			CubeLevel cubeLevel  = null ; 
	    			if(filter.getDataid()!=null){
	    				for(Dimension dim : cube.getDimension()){
	    					for(CubeLevel level : dim.getCubeLevel()){
	    						if(filter.getDataid()!=null && filter.getDataid().equals(level.getId())){
	    							cubeLevel = level  ;
	    							filter.setLevel(level) ;
	    						}
	    						if(filter.getParentFilter()!=null&&filter.getParentFilter().getDataid().equals(level.getId())){
		    						filter.getParentFilter().setLevel(level) ;
	    						}
	    						
	    					}
	    				}
	    			}
	    			if(cubeLevel!=null){
		    			model.setFilters(analyzerReport.getFilters()) ;
		    			Object value =  CacheHelper.getDistributedDictionaryCacheBean().getCacheObject("system.config.report.CubeFilterStyle", "rivues") ;
		    			if(value!=null&&value.toString().equals("false")){//使用sql进行级联并填充过滤器的值
		    				cube.setDstype(RivuDataContext.CubeEnum.TABLE.toString());
		    			}
		    			DataSource ds = ServiceHelper.getDataModelService(cube) ;
		    			QueryText queryText = ds.getQuery(model, cube, request, cubeLevel , filter.getParentValue() , null , useStaticFilter , filter) ;
	    				try {
	    					/**
	    					 * 读缓存先
	    					 */
	    					ReportData reportData = null ;
	    					String key = queryText!=null && queryText.getQueryText()!=null ? RivuTools.md5(queryText.getQueryText()) : null;
	    					reportData = (ReportData)CacheHelper.getDistributedReporyDataCacheBean().getCacheObject(key , null) ;
	    					if(!cache||updateCache || reportData==null){
	    						reportData = ds.getData(model , analyzerReport.getRequestParamValues(), cube, request, false, queryText, null) ;
	    						/**
	    						 * 如果启用了缓存，则记录
	    						 */
	    						CacheHelper.getDistributedReporyDataCacheBean().delete(key, null);
	    						if(cache){
	    							CacheHelper.getDistributedReporyDataCacheBean().put(key , reportData, null);
	    						}
	    					}
	    					if(cube.getDstype().equals(RivuDataContext.CubeEnum.TABLE.toString())){
	    						if(reportData.getRow()==null){
	    							reportData.setRow(reportData.getCol()) ;
	    						}
	    						if(reportData.getRow()!=null && reportData.getRow().getTitle()!=null){
	    							List<Level> titleList = reportData.getRow().getTitle().get(0) ;
	    							if(titleList.size()>0 && reportData.getData()!=null && reportData.getData().size()>0){
	    								Level level = titleList.remove(0) ;
	    								for(int i=0 ; i<reportData.getData().size() ; i++){
	    									ValueData valueData = reportData.getData().get(i).get(0) ;
	    									level = (Level) RivuTools.toObject(RivuTools.toBytes(level)) ;
	    									level.setName(valueData.getForamatValue()) ;
	    									titleList.add(level) ;
	    								}
	    							}
	    						}
	    					}
	    					if((!RivuDataContext.FilterModelType.SELECT.toString().equals(filter.getModeltype()))&&reportData.getRow()!=null&&reportData.getRow().getTitle()!=null&&reportData.getRow().getTitle().size()>1){
	    						List<List<Level>> titles = new ArrayList<List<Level>>();
	    						titles.add(reportData.getRow().getTitle().get(reportData.getRow().getTitle().size()-1));
	    						reportData.getRow().setTitle(titles);
	    					}
							filter.setReportData(reportData) ;
						} catch (Exception e) {
							e.printStackTrace();
						}
	    			}
    			}
    		}
    	}
    }
    
    
    public ReportFilter fillFilterValue(AnalyzerReport analyzerReport , boolean cache, AnalyzerReportModel model ,ReportFilter filter, HttpServletRequest request ,  boolean useStaticFilter){
    	if(analyzerReport!=null && analyzerReport.getFilters()!=null && analyzerReport.getFilters().size()>0){
    		for(ReportFilter filtertemp : analyzerReport.getFilters()){//设置上一级的默认值
    			if(!StringUtils.isBlank(filtertemp.getCascadeid())){
    				for(ReportFilter filter2 : analyzerReport.getFilters()){
    					if(filter2.getId().equals(filtertemp.getCascadeid())){
    						filter2.setParentValue(filtertemp.getRequestvalue()==null||(filtertemp.getRequestvalue()!=null&&filtertemp.getRequestvalue().trim().length()==0)?filtertemp.getDefaultvalue():filtertemp.getRequestvalue());
    						filter2.setParentFilter(filtertemp);
    						break;
    					}
    				}
    				
    			}
    		}
			
			for(ReportFilter filtertemp : analyzerReport.getFilters()){
				//取得没有格式的过滤器值
				
				if(filtertemp.getDefaultvalue()!=null&& filtertemp.getDefaultvalue().indexOf("].[")>-1){
					String[] strs = filtertemp.getDefaultvalue().replaceAll("\\]  ,  \\[", "(ooo)").replaceAll(",", "\\(-=-\\)").replaceAll("\\(ooo\\)", "\\],\\[").split(",");
					StringBuffer sb = new StringBuffer();
					for (String string : strs) {
						string = string.replaceAll(",", "\\(-=-\\)");
						if(sb.toString().length()>0){
							sb.append(",");
						}
						string = string.replaceAll("\\(-=-\\)", ",");
						sb.append(string.substring(string.lastIndexOf("["), string.length()).trim());
					}
					filtertemp.setNoformatvalue(sb.toString());
				}else{
					filtertemp.setNoformatvalue(filtertemp.getDefaultvalue());
				}
				if(filtertemp.getRequestvalue()!=null){
					if(filtertemp.getRequestvalue().indexOf("].[")>-1){
						String[] strs = filtertemp.getRequestvalue().split(",");
	    				StringBuffer sb = new StringBuffer();
	    				for (String string : strs) {
	    					string = string.trim();
							if(sb.toString().length()>0){
								sb.append(",");
							}
							sb.append(string.substring(string.lastIndexOf("["), string.length()).trim());
						}
	    				filtertemp.setNoformatvalue(sb.toString());
					}else{
						filtertemp.setNoformatvalue(filtertemp.getRequestvalue());
					}
				}
				if(filter.getNoformatvalue()!=null){
					filtertemp.setNoformatvalue(filtertemp.getNoformatvalue().replace("[", "'"));
					filtertemp.setNoformatvalue(filtertemp.getNoformatvalue().replace("]", "'"));
				}
				//取得没有格式的过滤器值end
			}
			
			if(filter.getParentFilter()!=null&&StringUtils.isBlank(filter.getParentValue()))return filter;
			
			if(model==null || !model.getId().equals(filter.getModelid())){
				model = getReportModel(analyzerReport  , filter.getModelid()) ;
			}
			if(model!=null && filter.getReportData()==null && RivuDataContext.FilterConValueType.AUTO.toString().equals(filter.getConvalue())){
				PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(model.getPublishedcubeid()) ;
    			Cube cube = publishedCube.getCube() ;
    			CubeLevel cubeLevel  = null ; 
    			if(filter.getDataid()!=null){
    				for(Dimension dim : cube.getDimension()){
    					for(CubeLevel level : dim.getCubeLevel()){
    						if(filter.getDataid().equals(level.getId())){
    							cubeLevel = level  ;
    							filter.setLevel(level) ;
    						}
    						if(filter.getParentFilter().getDataid().equals(level.getId())){
    							filter.getParentFilter().setLevel(level) ;
    						}
    					}
    				}
    			}
    			if(cubeLevel!=null){
	    			model.setFilters(analyzerReport.getFilters()) ;
	    			Object value =  CacheHelper.getDistributedDictionaryCacheBean().getCacheObject("system.config.report.CubeFilterStyle", "rivues") ;
	    			if(value!=null&&value.toString().equals("false")){//使用sql进行级联并填充过滤器的值
	    				cube.setDstype(RivuDataContext.CubeEnum.TABLE.toString());
	    			}
	    			DataSource ds = ServiceHelper.getDataModelService(cube) ;
	    			QueryText queryText = ds.getQuery(model, cube, request, cubeLevel , filter.getParentValue() , null , useStaticFilter , filter) ;
    				try {
    					
    					/**
    					 * 读缓存先
    					 */
    					ReportData reportData = null ;
    					String key = queryText!=null && queryText.getQueryText()!=null ? RivuTools.md5(queryText.getQueryText()) : null;
    					reportData = (ReportData)CacheHelper.getDistributedReporyDataCacheBean().getCacheObject(key , null) ;
    					if(!cache||reportData==null){
    						reportData = ds.getData(model , analyzerReport.getRequestParamValues(), cube, request, false, queryText, null) ;
    						/**
    						 * 如果启用了缓存，则记录
    						 */
    						CacheHelper.getDistributedReporyDataCacheBean().delete(key, null);
    						if(cache){
    							CacheHelper.getDistributedReporyDataCacheBean().put(key , reportData, null);
    						}
    					}
    					
    					
    					if(cube.getDstype().equals(RivuDataContext.CubeEnum.TABLE.toString())){
    						if(reportData.getRow()==null){
    							reportData.setRow(reportData.getCol()) ;
    						}
    						if(reportData.getRow()!=null && reportData.getRow().getTitle()!=null){
    							List<Level> titleList = reportData.getRow().getTitle().get(0) ;
    							if(titleList.size()>0 && reportData.getData()!=null && reportData.getData().size()>0){
    								Level level = titleList.remove(0) ;
    								for(int i=0 ; i<reportData.getData().size() ; i++){
    									ValueData valueData = reportData.getData().get(i).get(0) ;
    									level = (Level) RivuTools.toObject(RivuTools.toBytes(level)) ;
    									level.setName(valueData.getForamatValue()) ;
    									titleList.add(level) ;
    								}
    							}
    						}
    					}
    					
    					if((!RivuDataContext.FilterModelType.SELECT.toString().equals(filter.getModeltype()))&&reportData.getRow()!=null&&reportData.getRow().getTitle()!=null&&reportData.getRow().getTitle().size()>1){
    						List<List<Level>> titles = new ArrayList<List<Level>>();
    						titles.add(reportData.getRow().getTitle().get(reportData.getRow().getTitle().size()-1));
    						reportData.getRow().setTitle(titles);
    					}
						filter.setReportData(reportData) ;
					} catch (Exception e) {
						e.printStackTrace();
					}
    			}
			}
    		
    	}
    	return filter;
    }
    
    public QueryText filterQueryText(AnalyzerReport analyzerReport , AnalyzerReportModel model , HttpServletRequest request ,  boolean useStaticFilter , ReportFilter filter){
    	QueryText queryText = null;
    	if(analyzerReport!=null && analyzerReport.getFilters()!=null && analyzerReport.getFilters().size()>0){
    		for(ReportFilter filtertemp : analyzerReport.getFilters()){//设置上一级的默认值
    			if(!StringUtils.isBlank(filtertemp.getCascadeid())){
    				for(ReportFilter filter2 : analyzerReport.getFilters()){
    					if(filter2.getId().equals(filtertemp.getCascadeid())){
    						filter2.setParentValue(filtertemp.getRequestvalue()==null||(filtertemp.getRequestvalue()!=null&&filtertemp.getRequestvalue().trim().length()==0)?filtertemp.getDefaultvalue():filtertemp.getRequestvalue());
    						filter2.setParentFilter(filtertemp);
    						break;
    					}
    				}
    				
    			}
    		}
				
			
			for(ReportFilter filtertemp : analyzerReport.getFilters()){
				//取得没有格式的过滤器值
				
				if(filtertemp.getDefaultvalue()!=null&& filtertemp.getDefaultvalue().indexOf("].[")>-1){
					String[] strs = filtertemp.getDefaultvalue().replaceAll("\\]  ,  \\[", "(ooo)").replaceAll(",", "\\(-=-\\)").replaceAll("\\(ooo\\)", "\\],\\[").split(",");
					StringBuffer sb = new StringBuffer();
					for (String string : strs) {
						string = string.replaceAll(",", "\\(-=-\\)");
						if(sb.toString().length()>0){
							sb.append(",");
						}
						string = string.replaceAll("\\(-=-\\)", ",");
						sb.append(string.substring(string.lastIndexOf("["), string.length()).trim());
					}
					filtertemp.setNoformatvalue(sb.toString());
				}else{
					filtertemp.setNoformatvalue(filtertemp.getDefaultvalue());
				}
				if(filtertemp.getRequestvalue()!=null){
					if(filtertemp.getRequestvalue().indexOf("].[")>-1){
						String[] strs = filtertemp.getRequestvalue().split(",");
	    				StringBuffer sb = new StringBuffer();
	    				for (String string : strs) {
	    					string = string.trim();
							if(sb.toString().length()>0){
								sb.append(",");
							}
							sb.append(string.substring(string.lastIndexOf("["), string.length()).trim());
						}
	    				filtertemp.setNoformatvalue(sb.toString());
					}else{
						filtertemp.setNoformatvalue(filtertemp.getRequestvalue());
					}
				}
				if(filter.getNoformatvalue()!=null){
					filtertemp.setNoformatvalue(filtertemp.getNoformatvalue().replace("[", "'"));
					filtertemp.setNoformatvalue(filtertemp.getNoformatvalue().replace("]", "'"));
				}
				//取得没有格式的过滤器值end
			}
			
			if(model==null || !model.getId().equals(filter.getModelid())){
				model = getReportModel(analyzerReport  , filter.getModelid()) ;
			}
			if(model!=null && filter.getReportData()==null && RivuDataContext.FilterConValueType.AUTO.toString().equals(filter.getConvalue())){
				PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(model.getPublishedcubeid()) ;
    			Cube cube = publishedCube.getCube() ;
    			CubeLevel cubeLevel  = null ; 
    			if(filter.getDataid()!=null){
    				for(Dimension dim : cube.getDimension()){
    					for(CubeLevel level : dim.getCubeLevel()){
    						if(filter.getDataid().equals(level.getId())){
    							cubeLevel = level  ;
    							filter.setLevel(level) ;
    						}
    						if(filter.getParentFilter()!=null&&filter.getParentFilter().getDataid().equals(level.getId())){
    							filter.getParentFilter().setLevel(level) ;
    						}
    					}
    				}
    			}
    			if(cubeLevel!=null){
	    			model.setFilters(analyzerReport.getFilters()) ;
	    			Object value =  CacheHelper.getDistributedDictionaryCacheBean().getCacheObject("system.config.report.CubeFilterStyle", "rivues") ;
	    			if(value!=null&&value.toString().equals("false")){//使用sql进行级联并填充过滤器的值
	    				cube.setDstype(RivuDataContext.CubeEnum.TABLE.toString());
	    			}
	    			DataSource ds = ServiceHelper.getDataModelService(cube) ;
	    			queryText = ds.getQuery(model, cube, request, cubeLevel , filter.getParentValue() , null , useStaticFilter , filter) ;
    			}
			}
    	}
		return queryText ;
    }
    
    /**
     * 获取过滤条件的 下拉列表值
     * @param analyzerReport
     * @param model
     */
    public void fillFilterValue(AnalyzerReport analyzerReport , HttpServletRequest request ,  boolean useStaticFilter){
    	if(analyzerReport!=null && analyzerReport.getFilters()!=null && analyzerReport.getFilters().size()>0){
    		for(ReportFilter filter : analyzerReport.getFilters()){
    			AnalyzerReportModel model = getReportModel(analyzerReport  , filter.getModelid()) ;
    			if(model==null || !model.getId().equals(filter.getModelid())){
    				model = getReportModel(analyzerReport  , filter.getModelid()) ;
    			}
    			if(model!=null && filter.getReportData()==null && RivuDataContext.FilterConValueType.AUTO.toString().equals(filter.getConvalue())){
    				PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(model.getPublishedcubeid()) ;
	    			Cube cube = publishedCube.getCube() ;
	    			CubeLevel cubeLevel  = null ; 
	    			if(filter.getDataid()!=null){
	    				for(Dimension dim : cube.getDimension()){
	    					for(CubeLevel level : dim.getCubeLevel()){
	    						if(filter.getDataid()!=null && filter.getDataid().equals(level.getId())){
	    							cubeLevel = level  ;
	    							filter.setLevel(level) ;
	    							break ;
	    						}
	    					}
	    				}
	    			}
	    			if(cubeLevel!=null){
		    			model.setFilters(analyzerReport.getFilters()) ;
		    			Object value =  CacheHelper.getDistributedDictionaryCacheBean().getCacheObject("system.config.report.CubeFilterStyle", "rivues") ;
		    			if(value!=null&&value.toString().equals("false")){//使用sql进行级联并填充过滤器的值
		    				cube.setDstype(RivuDataContext.CubeEnum.TABLE.toString());
		    			}
		    			DataSource ds = ServiceHelper.getDataModelService(cube) ;
		    			QueryText queryText = ds.getQuery(model, cube, request, cubeLevel , null , null , useStaticFilter , filter) ;
	    				try {
	    					ReportData reportData = ds.getData(model , analyzerReport.getRequestParamValues() , cube, request, false, queryText, null) ;
	    					if(cube.getDstype().equals(RivuDataContext.CubeEnum.TABLE.toString())){
	    						if(reportData.getRow()==null){
	    							reportData.setRow(reportData.getCol()) ;
	    						}
	    						if(reportData.getRow()!=null && reportData.getRow().getTitle()!=null){
	    							List<Level> titleList = reportData.getRow().getTitle().get(0) ;
	    							if(titleList.size()>0 && reportData.getData()!=null && reportData.getData().size()>0){
	    								Level level = titleList.remove(0) ;
	    								for(int i=0 ; i<reportData.getData().size() ; i++){
	    									ValueData valueData = reportData.getData().get(i).get(0) ;
	    									level = (Level) RivuTools.toObject(RivuTools.toBytes(level)) ;
	    									level.setName(valueData.getForamatValue()) ;
	    									titleList.add(level) ;
	    								}
	    							}
	    						}
	    					}
							filter.setReportData(reportData) ;
						} catch (Exception e) {
							e.printStackTrace();
						}
	    			}
    			}
    		}
    	}
    }
    
    /**
     * 兼容功能，增加了 是否更新缓存的选项
     * @param view
     * @param report
     * @param request
     * @return
     * @throws Exception
     */
    public ModelAndView createModelAndView(ModelAndView view ,PublishedReport report , HttpServletRequest request,boolean isLoadReportData) throws Exception{
    	return createModelAndView(view , report ,null, request , false , null , true , false,isLoadReportData) ;
    }
    /**
     * 兼容功能，增加了 是否更新缓存的选项
     * @param view
     * @param report
     * @param request
     * @return
     * @throws Exception
     */
    public ModelAndView createModelAndView(ModelAndView view ,boolean isLoadReportData,PublishedReport report , HttpServletRequest request, AnalyzerReportModel reportModel) throws Exception{
    	return createModelAndView(view , report ,null, request , false , reportModel , true , true,isLoadReportData) ;
    }
    
    public ModelAndView createModelAndView(ModelAndView view ,PublishedReport report ,Cube cube, HttpServletRequest request , AnalyzerReportModel reportModel) throws Exception{
    	return createModelAndView(view , report ,cube, request , false , reportModel , true , true,true) ;
    }
    
    /**
     * 兼容功能，增加了 是否显示全部参数  ， 为 PlayerDesign 使用
     * @param view
     * @param report
     * @param request
     * @return
     * @throws Exception
     */
    public ModelAndView createModelAndView(ModelAndView view ,PublishedReport report , HttpServletRequest request , AnalyzerReportModel reportModel , boolean displayAllFilters,boolean isLoadReportData) throws Exception{
    	return createModelAndView(view , report ,null, request , false , reportModel , displayAllFilters , false,isLoadReportData) ;
    }
    /**
     * 处理没数据时也显示表头
     * @param view
     * @param report
     * @param request
     * @return
     * @throws Exception
     */
    public ModelAndView createModelAndView(ModelAndView view ,PublishedReport report ,Cube drilldowncube, HttpServletRequest request , boolean updateCache , AnalyzerReportModel model , boolean displayAllFilters , boolean useStaticFilter,boolean isLoadReportData) throws Exception{
    	//统一记录report操作日志
    	if(queryLog!=null){
    		User user = super.getUser(request);
    		queryLog.setReportdic(this.getParent(report.getDicid(), report.getOrgi())+"/"+report.getName()+".rpt") ;
    		queryLog.setUserid(user.getId());
    		queryLog.setUsermail(user.getEmail());
    		queryLog.setUsername(user.getUsername());
    	}
    	
		
    	view.addObject("report", report) ;
    	//System.out.println("model的id的值为:"+model.getPublishedcubeid());//有数据的时候:model的id=4028d88f47d2de6b0147d3184d4d056c  没数据的时候:model的id=4028d88f47d2de6b0147d3184d4d056c
    	if(report.getReportcontent()!=null && report.getReportcontent().length()>0){
//    		System.out.println("report:"+report.getReportcontent());
    		AnalyzerReport analyzerReport = report.getReport() ;
    		if(view.getModel().get("loadata")!=null){
    			analyzerReport.setLoadata(true);
    		}
    		if(displayAllFilters){
    			view.addObject("filters",analyzerReport.getFilters());
    		}else{
    			view.addObject("filters",RivuTools.getRequestFilters(analyzerReport.getFilters()));
    		}
    		view.addObject("analyzerReport", analyzerReport) ; 
    		/**
    		 * 处理 查询条件，从 模型中获取数据列表
    		 */
    		fillFilterValue(analyzerReport , updateCache , report.isCache() , model , request , useStaticFilter);
    		//存过滤器设置的上限
    		Object obj =  (String) CacheHelper.getDistributedDictionaryCacheBean().getCacheObject("system.config.report.filter.auto.size", report.getOrgi()) ;
    		int filter_auto_size = 1000;
    		if(obj!=null){
    			filter_auto_size = Integer.parseInt(obj.toString());
    			view.addObject("filter_auto_size", filter_auto_size);
    		}
    		
    		/**
    		 * 
    		 */
    		if(analyzerReport.getModel().size()>0){
    			if(model == null){
    				if(request.getParameter("modelid")!=null){
    					for(AnalyzerReportModel tempModel : analyzerReport.getModel()){
    						if(request.getParameter("modelid").equals(tempModel.getId())){
    							model = tempModel ;
    						}
    					}
    				}else{
    					model = analyzerReport.getModel().get(0) ;
    				}
    				view.addObject("reportModel", model) ;
	    			/**
	    			 * 动态报表创建以后 的 publishedcubeid 为NULL ， 所以需要做判断
	    			 */
	    			if(model.getPublishedcubeid()!=null && model.getPublishedcubeid().length()>0){
		    			PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(model.getPublishedcubeid()) ;
		    			if(publishedCube!=null){
		    				Cube cube = publishedCube.getCube(RivuDataContext.getUser(request)) ;
		    				view.addObject("cube", cube) ;
		    				if(isLoadReportData){
			    				model.setCube(cube) ;
			    				ReportData reportData  = null;
			    				if(drilldowncube==null){
			    					reportData  = ServiceHelper.getReportService().service(request , model , analyzerReport , true , getQueryLog() , report.isCache() , updateCache) ;
			    				}else{
			    					reportData  = ServiceHelper.getReportService().service(request , model ,drilldowncube, analyzerReport , true , getQueryLog() , report.isCache() , updateCache) ;
			    				}
	
			    				model.setReportData(reportData) ;
			    				view.addObject("reportData", reportData) ;
		    				}

		    			}else{
		    				/**
		    				 * 清空报表所有内容
		    				 */
		    				analyzerReport.getModel().clear();
		    				analyzerReport.getFilters().clear();
		    				updateCacheReport(request , report , analyzerReport , report.getOrgi()) ;
		    			}
	    			}
    			}else{
	    			view.addObject("reportModel", model) ;
	    			/**
	    			 * 动态报表创建以后 的 publishedcubeid 为NULL ， 所以需要做判断
	    			 */
	    			if(model.getPublishedcubeid()!=null && model.getPublishedcubeid().length()>0){
		    			PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(model.getPublishedcubeid()) ;
		    			if(publishedCube!=null){
		    				Cube cube = publishedCube.getCube(RivuDataContext.getUser(request)) ;;
			    			view.addObject("cube", cube) ;
			    			if(isLoadReportData){
				    			model.setCube(cube) ;
				    			ReportData reportData  = null;
				    			if(drilldowncube==null){
				    				reportData  = ServiceHelper.getReportService().service(request , model , analyzerReport , true , getQueryLog() , report.isCache() , updateCache) ;
				    			}else{
				    				reportData  = ServiceHelper.getReportService().service(request , model ,drilldowncube, analyzerReport , true , getQueryLog() , report.isCache() , updateCache) ;
				    			} 
				    			model.setReportData(reportData) ;
				    			view.addObject("reportData", reportData) ;
			    			}
		    			}else{
		    				/**
		    				 * 清空报表所有内容
		    				 */
		    				analyzerReport.getModel().clear();
		    				analyzerReport.getFilters().clear();
		    				updateCacheReport(request , report , analyzerReport , report.getOrgi()) ;
		    			}
		    			
		    			
	    			}
    			}
    		}
    	}
    	
//    	System.out.println("if后");
//    	for (FirstTitle f : model.getReportData().getRow().getFirstTitle()) {
//			System.out.println("表头的name值为："+f.getName()+"    表头的Rename的值为:"+f.getRename());
//		}
    	return view ;
    }
    
    /**
     * 兼容功能，增加了 是否更新缓存的选项
     * @param view
     * @param report
     * @param request
     * @return
     * @throws Exception
     */
    public ModelAndView createReportView(ModelAndView view ,PublishedReport report , HttpServletRequest request) throws Exception{
    	return createReportView(view , report , request , false , true , true) ;
    }
    
    /**
     * 兼容功能，增加了 是否显示全部参数  ， 为 PlayerDesign 使用
     * @param view
     * @param report
     * @param request
     * @return
     * @throws Exception
     */
    public ModelAndView createReportView(ModelAndView view ,PublishedReport report , HttpServletRequest request , AnalyzerReportModel reportModel , boolean displayAllFilters) throws Exception{
    	return createReportView(view , report , request , false , displayAllFilters , false) ;
    }
    
    /**
     * 
     * @param view
     * @param report
     * @param request
     * @return
     * @throws Exception
     */
    public ModelAndView createReportView(ModelAndView view ,PublishedReport report , HttpServletRequest request , boolean updateCache , boolean displayAllFilters , boolean useStaticFilter) throws Exception{
    	if(report.getBlacklist()!=null && report.getBlacklist().equals(RivuDataContext.ReportTypeEnum.DASHBOARD.toString())){
			DataDic dashboard = null ;
			if(report.getRolename()!=null && report.getRolename().equals(RivuDataContext.ReportTypeEnum.DASHBOARD.toString())){
				dashboard = ReportFactory.getReportInstance().getReportDic(report.getId(), report.getOrgi(), super.getUser(request)) ;
			}else{
				dashboard = ReportFactory.getReportInstance().getReportDic(report.getDicid(), report.getOrgi(), super.getUser(request)) ;
			}
			view.addObject("dashboard", dashboard) ;
			List<PublishedReport> reportList = ReportFactory.getReportInstance().getReportList(dashboard.getId(), report.getOrgi(), super.getUser(request), dashboard.getTabtype(), RivuDataContext.ReportTypeEnum.REPORT.toString()) ; 
	    	view.addObject("reportList", reportList) ;
	    	if(reportList.size()>0 && report.getRolename()!=null && report.getRolename().equals(RivuDataContext.ReportTypeEnum.DASHBOARD.toString())){
	    		report = reportList.get(0) ;
	    		view.addObject("reportid" , report.getId()) ;
	    	}
		}
    	view.addObject("report", report) ;
    	if(report.getReportcontent()!=null && report.getReportcontent().length()>0){
//    		System.out.println("report:"+report.getReportcontent());
    		AnalyzerReport analyzerReport = report.getReport() ;
    		if(displayAllFilters){
    			view.addObject("filters",analyzerReport.getFilters());
    		}else{
    			view.addObject("filters",RivuTools.getRequestFilters(analyzerReport.getFilters()));
    		}
    		/**
    		 * 处理 查询条件，从 模型中获取数据列表
    		 */
    		fillFilterValue(analyzerReport , request , useStaticFilter);
    		view.addObject("analyzerReport", analyzerReport) ;
    		/**
    		 * 
    		 */
    		if(analyzerReport.getModel().size()>0){
    			for(AnalyzerReportModel model : analyzerReport.getModel()){
    				/**
	    			 * 动态报表创建以后 的 publishedcubeid 为NULL ， 所以需要做判断
	    			 */
	    			if(model.getPublishedcubeid()!=null && model.getPublishedcubeid().length()>0){
		    			PublishedCube publishedCube = CubeFactory.getCubeInstance().getCubeByID(model.getPublishedcubeid()) ;
		    			if(publishedCube!=null){
		    				model.setCube(publishedCube.getCube(RivuDataContext.getUser(request))) ;
			    			ReportData reportData  = ServiceHelper.getReportService().service(request , model , analyzerReport , true , getQueryLog() , report.isCache() , updateCache) ;
			    			model.setReportData(reportData) ;
		    			}
		    			
	    			}
    			}
    		}
    	}
    	return view ;
    }
    /**
     * 固定参数传入
     * @param report
     * @param request
     */
    public void processRequestParam(AnalyzerReport report , HttpServletRequest request , boolean hidden){
    	Map<String, Object> values = new HashMap<String, Object>();
		if(request!=null){
			Enumeration<String> param = request.getParameterNames() ;
			while(param.hasMoreElements()){
				String name = param.nextElement() ;
				if(name.startsWith("stat") && request.getParameter(name)!=null && request.getParameter(name).trim().length()>0){
					values.put(name, request.getParameter(name)) ;
				}
			}
		}
		if(hidden){
			report.getHiddenParamValues().putAll(values);
		}
		report.setRequestParamValues(values) ;
		report.getRequestParamValues().putAll(report.getHiddenParamValues());
    }
    
    
    @SuppressWarnings("unchecked")
	public String getParent(String id,String orgi){
		StringBuffer strb = new StringBuffer() ;
		List<DataDic> diclist = super.getService().findAllByCriteria(DetachedCriteria.forClass(DataDic.class).add(Restrictions.eq("orgi",orgi)));
		DataDic parent = null ;
		while(parent==null){
			for(DataDic type : diclist){
				if(type.getId().equals(id)){
					parent = type ;
					id = parent.getParentid();
					break ;
				}
			}
			if(parent!=null){
				strb.insert(0, parent.getName()).insert(0,"/");
				parent = null;
			}else{
				break ;
			}
		}
		if(strb.length()==0){
			strb.append("/") ;
		}
		return strb.toString();
	}
}
